<?php

namespace ApiWF\Controller;

use Common\Controller\ApibaseController;
use Think\Exception;

class MerchController extends ApibaseController
{

    public function index()
    {


        $category_list = D('MerchCategory')->where(['taxonomy' => 'merch', 'status' => 1])->field(['cate_id' => 'cid', 'name'])->order('listorder')->select();
        $cate_all = ['cid' => '0', 'name' => '全部'];
        array_unshift($category_list, $cate_all);

        $floor_list = D('MerchCategory')->where(['taxonomy' => 'floor', 'status' => 1])->field(['cate_id' => 'fid', 'name'])->order('listorder')->select();
        $floor_all = ['fid' => '0', 'name' => '全部'];
        array_unshift($floor_list, $floor_all);

        $recommend_cate_list = D('MerchCategory')->where(['taxonomy' => 'merch', 'status' => 1, 'istop' => 1])->field(['cate_id' => 'cid', 'name', 'smeta'])->order('listorder desc')->select();
        foreach ($recommend_cate_list as $key => $vo) {
            $recommend_cate_list[$key]['smeta'] = qiniu_mirror_image_url_merchant_category($vo);
        }
        $order_list = [
            ['name' => '默  认', 'order_type' => '0'],

            ['name' => '名称', 'order_type' => '2'],

            //['name' => '点赞升', 'order_type' => '4'],
            ['name' => '点赞数', 'order_type' => '3'],
            //['name' => '名称升', 'order_type' => '1'],
        ];
        $data = compact('category_list', 'floor_list', 'merchants', 'recommend_cate_list', 'order_list');
        $this->json_doc = ['merch_status' => '状态,1-正常，-1-删除,2-推荐商家'];
        $this->jsonReturn($data);
    }

    public function search()
    {
        //获取已近点赞的商家
        $uid = $this->parseTokenUID();
        $praised_merch_ids = D('MerchUserPraises')->where(['uid' => $uid])->field('mid')->select();
        $praised_merch_ids = array_column($praised_merch_ids, 'mid');


        $where['merch_status'] = ['GT', 0];

        $cid = I('cid', 0);
        if (!empty($cid)) {
            $where['cid'] = $cid;
        }


        $fid = I('fid', 0);
        if (!empty($fid)) {
            $where['fid'] = $fid;
        }

        $keyword = I('keyword');
        if (!empty($keyword)) {
            $keyword = trim($keyword);
            $where['_string'] = " `merch_name` LIKE '%$keyword%' OR `merch_description` LIKE '%$keyword%'";
        }

        $order_type = I('order_type', 0, 'intval');
        //默认
        //推荐 和 更新时间 降序
        $order_string = ['merch_status' => 'desc', 'update_time' => 'desc'];

        if ($order_type === 1) {
            $order_string = "merch_name DESC";
        }
        if ($order_type === 2) {
            $order_string = "merch_name";
        }
        if ($order_type === 3) {
            $order_string = "`merch_praise` desc";
        }
        if ($order_type === 4) {
            $order_string = "`merch_praise`";
        }


        $data = $this->pageHelper(D('MerchView'), $where, $order_string);
        foreach ($data['list'] as $key => $item) {
            $data['list'][$key]['merch_pics'] = qiniu_mirror_image_url_merchant($item);
            $mid = $item['id'];
            if (in_array($mid, $praised_merch_ids)) {
                $data['list'][$key]['is_current_user_praised'] = 1;
            } else {
                $data['list'][$key]['is_current_user_praised'] = 0;
            }
        }
        //$sql = M()->getLastSql();
        $this->jsonReturn($data);
    }

    public function praise()
    {


        $uid = $this->parseTokenUID();
        $mid = I('merchant_id', 0, 'intval');

        $exist = D('Merch')->where(['id'=>$mid,'merch_status'=>['GT',0]])->find();
        if(empty($exist)){
            $this->error('店铺不存在');
        }


        $praise_or_cancel = I('praise_or_cancel', 0, 'intval');

        $create_time = date("Y-m-d H:i:s", time());
        //判断今天是否点赞了
        $res = D('MerchUserPraises')->where(['uid' => $uid, 'mid' => $mid])->find();

//         if((time()-strtotime($res['create_time'])) >= 86400){
//
//         }


        if ($praise_or_cancel) {
            $where = compact('uid', 'mid', 'create_time');
            //点赞
            D('Merch')->where(['id' => $mid])->setInc('merch_praise', 1);
            D('MerchUserPraises')->add($where);
            $this->success('点赞成功');
        } else {
            $where = compact('uid', 'mid');
            //取消点赞
            D('Merch')->where(['id' => $mid, 'merch_praise' => ['GT', 0]])->setDec('merch_praise', 1);

            $where = compact('uid', 'mid');
            D('MerchUserPraises')->where($where)->delete();
            $this->success('取消成功');
        }
    }
    //废弃
    public function detail()
    {
        $uid = $this->parseTokenUID();
        $mid = I('merchant_id', 0, 'intval');
        $merch_info = D('MerchView')->where(['id' => $mid,'Merch.merch_status'=>['GT',0]])->find();
        if (empty($merch_info)) {
            $this->error('店铺不存在');
        }
        $merch_info['merch_pics'] = qiniu_mirror_image_url_merchant($merch_info);
        htmlStringToPlainStirngArray($merch_info, 'merch_content');

        $where['goods_status'] = ['GT',0];
        $where['mid'] = $mid;
        $goods = D('MerchGoods')->where($where)->order('create_time desc')->select();
        foreach ($goods as $key => $good) {
            $goods[$key]['goods_pics'] = qiniu_mirror_image_url_merch_good($good);
            htmlStringToPlainStirngArray($goods[$key], 'goods_content');
        }

        $where = [
            'status' => ['GT', 0],
            'mid' => $mid,
        ];

        $comments = D('MerchCommentsView')->where($where)->order('create_time desc')->select();
        foreach ($comments as $key => $vo) {
            $comments[$key]['avatar'] = qiniu_mirror_image_url($vo['avatar']);
            $comments[$key]['create_time'] = friendlyDate($vo['create_time']);
        }
        //是否收藏
        $where = [
            'uid' => $uid,
            'mid' => $mid
        ];
        $res = D('UserMerchFavorites')->where($where)->find();
        $merch_info['is_favorite'] = empty($res) ? 0 : 1;

        $praise = D('MerchUserPraises')->where($where)->find();

//        if (!empty($praise)) {
//            $nowtime = time();
//            $praisetime = strtotime($praise['create_time']);
//
//            if ($nowtime - $praisetime <= 86400) {
//
//                $merch_info['is_praise'] = 1;
//            } else {
//                $merch_info['is_praise'] = 0;
//            }
//
//        } else {
//            $merch_info['is_praise'] = 0;
//        }
         $merch_info['is_praise'] = empty($praise) ? 0 : 1;


        $this->jsonReturn(compact('merch_info', 'goods', 'comments'));
    }


    public function commentPagination()
    {
        $mid = I('mid', 0, 'intval');
        $where = [
            'status' => ['GT', 0],
            'mid' => $mid,
        ];
        $order = 'create_time desc';
        $m = D('MerchCommentsView');
        $data = $this->pageHelper($m, $where, $order);

        $comments = $data['list'];
        foreach ($comments as $key => $vo) {
            $comments[$key]['avatar'] = qiniu_mirror_image_url($vo['avatar']);
            $comments[$key]['create_time'] = friendlyDate($vo['create_time']);
        }
        $data['list'] = $comments;

        $this->jsonReturn($data);
    }


    public function favorated()
    {
        $uid = $this->parseTokenUID();
        $mid = I('merchant_id', 0, 'intval');

        $exist = D('Merch')->where(['id'=>$mid,'merch_status'=>['GT',0]])->find();
        if(empty($exist)){
            $this->error('店铺不存在');
        }

        $favorate_or_cancel = I('favorate_or_cancel', 0, 'intval');

        $where = compact('uid', 'mid');
        if ($favorate_or_cancel) {
            //点赞
            D('Merch')->where(['id' => $mid])->setInc('merch_favorite_count', 1);
            D('UserMerchFavorites')->add($where);
            $this->success('收藏成功');
        } else {
            //取消点赞
            D('Merch')->where(['id' => $mid, 'merch_favorite_count' => ['GT', 0]])->setDec('merch_favorite_count', 1);
            D('UserMerchFavorites')->where($where)->delete();
            $this->success('取消收藏');
        }
    }

    public function addComment()
    {

        $uid = $this->parseTokenUID();
        $mid = I('merchant_id', 0, 'intval');
        $exist = D('Merch')->where(['id'=>$mid,'merch_status'=>['GT',0]])->find();
        if(empty($exist)){
            $this->error('店铺不存在');
        }

        $content = I('content', '');
        $content = removeEmoji($content);

        if (empty($content)) {
            $this->error('评论内容不为空!');
        }
        $data = compact('uid', 'mid', 'content');
        $data['create_time'] = date('Y-m-d H:i:s', time());

        try {
            D('MerchComments')->add($data);
            $this->success('添加评论成功,审核后可以查看');
        } catch (Exception $e) {
            $this->error('不支持emoji表情!');
        }
    }

    public function goodsDetail()
    {
        $goods_id = I('goods_id');

        $good_info = D('MerchGoods')->where(['id' => $goods_id,'goods_status'=>['GT',0]])->find();
        if (empty($good_info)) {
            $this->error('商品不存在');
        }
        $good_info['goods_pics'] = qiniu_mirror_image_url_merch_good($good_info);
        htmlStringToPlainStirngArray($good_info, 'goods_content');
        $this->jsonReturn($good_info);

    }


    public function merchNewDatil(){
        $uid = $this->parseTokenUID();
        $mid = I('merchant_id', 0, 'intval');
        $merch_info = D('Merch')->where(['id' => $mid,'merch_status'=>['GT',0]])->field('merch_name as share_title, merch_description as content,merch_pics as share_image,merch_praise')->find();
        if (empty($merch_info)) {
            $this->error('店铺不存在');
        }
        $smeta = json_decode($merch_info['share_image'],true);
        $avatar = $smeta['avatar'];
        $merch_info['share_image'] = qiniu_mirror_image_url($avatar,'imageView2/1/w/80/h/80');

        htmlStringToPlainStirngArray($merch_info, 'content');

        $where['goods_status'] = ['GT',0];
        $where['mid'] = $mid;

        //是否收藏
        $where = [
            'uid' => $uid,
            'mid' => $mid
        ];
        $res = D('UserMerchFavorites')->where($where)->find();
        $merch_info['isCollect'] = empty($res) ? 0 : 1;
        $praise = D('MerchUserPraises')->where($where)->find();
        $merch_info['isPraise'] = empty($praise) ? 0 : 1;
        $merch_info['shareUrl'] = C('host',null,'https://api.loongsin.com') . U('H5/Web/merch',['id'=>$mid]);

        $merch_info['shareTitle'] = $merch_info['share_title'];
        $merch_info['shareImage'] = $merch_info['share_image'];
        $merch_info['praiseCount'] = $merch_info['merch_praise'];
        unset($merch_info['share_image'],$merch_info['share_title'],$merch_info['merch_praise']);

        $this->jsonReturn2($merch_info);

    }



    //废弃
    public function comments()
    {
        $mid = I('id', 0, 'intval');
        $merch_info = D('MerchView')->where(['id' => $mid,'Merch.merch_status'=>['GT',0]])->find();
        if (empty($merch_info)) {
            $this->error('店铺不存在');
        }

        $where = [
            'status' => ['GT', 0],
            'mid' => $mid,
        ];

        $model =  D('MerchCommentsView');
        $order = 'create_time desc';

        $data =$this->pageHelper($model,$where,$order);

        $comments = $data['list'];
        foreach ($comments as $key => $vo) {
            $comments[$key]['avatar'] = qiniu_mirror_image_url($vo['avatar']);
            $comments[$key]['create_time'] = friendlyDate($vo['create_time']);
        }
        $data['list'] = $comments;

        $this->jsonReturn2($data);
    }


    public function shareGoodsDetail(){

        $id = I('id',0,'intval');
        $act_model = M("MerchGoods");
        $where['id'] = $id;
        $where['act_status'] = array('neq', '-1');
        $goods = $act_model->where($where)->field("id,goods_name as share_title,goods_description as share_content,goods_pics")->find();
        if ($goods) {
            $goods['goods_pics'] = qiniu_mirror_image_url_merch_good($goods);
            $host = C('host',null,'https://api.loogsin.com');
            $uri = U('/H5/Web/goods',['id'=>$id]);
            $goods['share_url'] = $host.$uri ;
            $this->jsonReturn2($goods);
        }
        else {
            $this->error('商品已经删除或者已经取消');
        }


    }



    public function h5CommentPullDownRefresh(){
        $max_id = I('max_id',0,'intval');
        $mid = I('mid', 0, 'intval');
        $page_size = I('page_size',16,'intval');

        $where = [
            'MerchComments.status' => ['GT', 0],
            'MerchComments.mid' => $mid,
        ];
        if($max_id >0){
            $where['MerchComments.id'] = ['GT',$max_id];
        }


        $order = 'create_time desc';
        $m = D('MerchCommentsView');
        $comments = $m->where($where)->order($order)->limit($page_size)->select();

        foreach ($comments as $key => $vo) {
            $comments[$key]['avatar'] = qiniu_mirror_image_url($vo['avatar']);
            $comments[$key]['create_time'] = friendlyDate($vo['create_time']);
        }
        $data['list'] = $comments;
        $data['max_id'] = $comments[0]['id'];

        $this->jsonReturn2($data);



    }

    };

